const db = require('../db/index.js');
//导入bcript模块
const bcript = require('bcryptjs');


//牧场入驻审路由处理
exports.farmAdd = (req, res) => {
  const { farm_name, address, contact_info, password } = req.body;
  //是否重名
  const sql = 'select * from farm where farm_name=?';
  db.query(sql, [farm_name], (error, results, fields) => {
    if (error) {
      return res.cc(err);
    }
    if (results.length> 0){
      return res.cc('该账号已存在');
    } else {
      //调用bcrypt.hashSync()对密码进行加密
      const passwordHash = bcript.hashSync(password, 10);
      const sql = ' insert into farm(farm_name,address,contact_info,password) values(?,?,?,?)';
      db.query(sql, [farm_name, address, contact_info, passwordHash], (error, results, fields) => {
        if (error) {
          return res.cc('添加账号失败');
        }
        // sql c成功执行 但是影响行数不等于1
        if(results.affectedRows !== 1) 
        {
          return res.cc('添加账号失败,请稍后再试');
        }
         //注册成功
         return res.cc(0, '添加账号成功');
      });
    }
  })

}

//牧场登录路由处理
exports.farmLogin = (req, res) => {
  const { farm_name, password } = req.body;
  const sql = ' select * from farm where farm_name=?';
  db.query(sql, [farm_name], (error, results, fields) => {
    if (error) {
      return res.cc(error);
    }
    // 没有该账号
    if (results.length !== 1) {
      return res.cc('账号不存在');
    }
    // console.log(results[0].password);
    //  //判断密码是否正确
     const compareResult =  bcript.compareSync(password, results[0].password)
     if(!compareResult) {
      return res.cc('密码错误');
     }
     //登录成功
     return res.send({
      code: 0,
      id: results[0].id,
      farm_name: results[0].farm_name,
      message: '登录成功',
     }
     )
    // return res.cc(0, '登录成功');
  });
}

